<?php

namespace WDB\Event;

/** 
 * event listening and raising class
 * invokes all attached iEventListener objects on raise() call
 * 
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
class Event extends \WDB\BaseCollection
{
    /**
     * Calls all attached event listeners.
     *
     * @param mixed $arg1,... arguments passed to listeners
     * @return array of results of listener calls
     */
    public function raise()
    {
        $returned_values = array();
        $arguments = func_get_args();
        foreach ($this as $listener)
        {
            $returned_values[] = call_user_func_array(array($listener, 'raise'), $arguments);
        }
        return $returned_values;
    }

    /**
     * Attaches a listener.
     *
     * @param iEventListener
     * @return bool false if listener object is already attached (will not be attached twice)
     */
    public function addListener(iEventListener $listener)
    {
        if (!in_array($listener, $this->contents))
        {
            $this[] = $listener;
            return TRUE;
        }
        return FALSE;
    }
    
    /**
     * Detaches a listener
     *
     * @param iEventListener
     * @return true if listener was found and detached
     */
    public function removeListener(iEventListener $listener)
    {
        $k = array_search($listener, $this->contents);
        if ($k !== FALSE)
        {
            unset($this[$k]);
            return TRUE;
        }
        return FALSE;
    }
}